//
//  CoinImageService.swift
//  Crypto
//
//  Created by DaleGuo on 2023/9/22.
//

import Combine
import Foundation
import SwiftUI

class CoinImageService {
    @Published var image: UIImage? = nil

    var imageSubscriber: AnyCancellable?

    let coin: CoinModel

    let folderName = "coin_images"

    let fileManager = LocalFileManager.instance

    init(coin: CoinModel) {
        self.coin = coin
        getCoinImage()
    }

    /// 尝试从FileManager中获取
    private func getCoinImage() {
        if let saveImage = fileManager.get(key: coin.id, folderName: folderName) {
            image = saveImage
            print("Get Image From File")
        } else {
            downloadCoinImage()
            print("Downloading From Internet")
        }
    }

    private func downloadCoinImage() {
        guard let url = URL(string: coin.image)
        else {
            return
        }

        // 如果不取消订阅，将会一直监听未来可能的数据，但我们知道不会有持续数据，所以要cancel
        imageSubscriber = NetWorkingManager.download(url: url)
            .tryMap { data -> UIImage? in
                UIImage(data: data)
            } // 直接用map解析data 为image
//            .decode(type: Image.self, decoder: JSONDecoder())
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: NetWorkingManager.handleCompletion, receiveValue: { [weak self] returnedImage in

                guard
                    let self = self, let downloadingImage = returnedImage
                else { return }
                self.image = returnedImage
                self.imageSubscriber?.cancel() // cancle sub
                self.fileManager.save(image: downloadingImage, key: coin.id, folderName: folderName) // 保存image到file
            })
    }
}
